package cn.fl.customer.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstCommRecService;
import cn.fl.customer.vo.CstCommRecVO;
import cn.fl.customer.vo.CstMidManInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import fl.customer.facade.customer.condition.CstCommRecQueryCondition;
import fl.customer.facade.customer.dto.CstCommRecDTO;

/**
 * @Description: 客户沟通记录表 控制层
 */
@Controller
@RequestMapping("/customer/cstcommrec")
public class CstCommRecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstCommRecController.class);

	/**
	 * CstCommRec 服务层BEAN
	 */
	@Autowired
	private ICstCommRecService cstCommRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstcommrec/custCstCommRecList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toListPage", "转到列表页面!cstId:"+cstId, CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到查看列表页面
	 */
	@RequestMapping(value = "/toDetailListPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstcommrec/custCstCommRecDetailList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toDetailListPage", "转到查看列表页面!cstId:"+cstId, CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstcommrec/custCstCommRecAdd");
		view.addObject("cId", id);
		view.addObject("cstId", cstId);
		List<KeyValueVO> commWayCdlist = this.cstCommRecService.searchCommWayCdList();
		view.addObject("searchSelectCommWayCdList", commWayCdlist);
		BaseLogUtils.info(logger, "toModifyPage", "转到新增/修改页面![id="+id+",cstId="+cstId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("customer/cstcommrec/custCstCommRecDetail");
		view.addObject("cId", id);
		BaseLogUtils.info(logger, "toDetailPage", "转到详情页面![id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		
		//如果客户ID有问题则直接返回空集合
		if(StringUtils.isBlank(cstId) || !StringUtils.isNumeric(cstId)){
			BaseLogUtils.info(logger, "initList", "客户主键参数不存在,直接返回空集合.", CurrentThreadContext.getCurrentUserName());
			return new ListPageVO<CstMidManInfoVO>();
		}
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstCommRecQueryCondition qc = new CstCommRecQueryCondition();
		qc.setCstId(Long.valueOf(cstId));
		List<String> orgCdList = new ArrayList<>();
		orgCdList.add(CurrentThreadContext.getCurrentOrgCd());
		qc.setOrgCdList(orgCdList);
		qc.setCurrUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);
		Pager pager = this.cstCommRecService.searchListPage(page);
		List<CstCommRecDTO> list = (List<CstCommRecDTO>) pager.getResultList();
		ListPageVO<CstCommRecDTO> listPage = new ListPageVO<CstCommRecDTO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeById", "删除主键参数不存在,直接返回空集合.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			Boolean pass = this.cstCommRecService.removeById(Long.valueOf(id));
			if(pass){
				BaseLogUtils.info(logger, "removeById", "删除成功.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeById", "删除失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除失败.[id="+id+"] , ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除失败.[id="+id+"] , ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "主键ID参数不存在.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CstCommRecVO vo = this.cstCommRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]" + ex.getMessage() + ",ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取.[id="+id+"]" + ex.getMessage() + ",ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CstCommRecVO entity = null;
		try {
			entity = getRequsetParams(request);
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.cstCommRecService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增失败. DATA:" + JSONObject.toJSONString(entity) + ", ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增失败. DATA:" + JSONObject.toJSONString(entity) + ", ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		CstCommRecVO entity = null;
		try {
			entity = getRequsetParams(request);
			entity.setId(Long.valueOf(id));
			boolean success = this.cstCommRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改失败. DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败. DATA:" + JSONObject.toJSONString(entity) + ", ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败. DATA:" + JSONObject.toJSONString(entity) + ", ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 */
	private CstCommRecVO getRequsetParams(HttpServletRequest request) {
		String commDt = request.getParameter("commDt");
		String commWayCd = request.getParameter("commWayCd");
		String respPsn = request.getParameter("respPsn");
		String linkman = request.getParameter("linkman");
		String contactNum = request.getParameter("contactNum");
		String briefRec = request.getParameter("briefRec");
		String feedbackRec = request.getParameter("feedbackRec");
		String rsnDesc = request.getParameter("rsnDesc");
		String cstId = request.getParameter("cstId");
		
		if (StringUtils.isBlank(cstId)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_ID_EMPTY);
		}
		
		if(StringUtils.isBlank(commDt) || !DateUtils.isDate(commDt, DateUtils.YYYY_MM_DD)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_COMM_DT);
		}
		
		if(StringUtils.isBlank(commWayCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_COMM_WAY);
		}
		
		if (StringUtils.isBlank(respPsn) || respPsn.length() > 20 || !StringUtils.isCustomerName(respPsn)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_RESP_PSN);
		}
		
		if (StringUtils.isBlank(linkman) || linkman.length() > 20 || !StringUtils.isCustomerName(linkman)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_LINK_MAN);
		}
		
		if(StringUtils.isBlank(contactNum) || !StringUtils.isMobilePhoneAndFixedPhone(contactNum)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_CONTACT_NUM);
		}
		
		if(StringUtils.isNotBlank(briefRec) && briefRec.length() > 250){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_BRIEF_REC);
		}
		
		if(StringUtils.isNotBlank(feedbackRec) && feedbackRec.length() > 250){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_FEEDBACK_REC);
		}
		
		if(StringUtils.isNotBlank(rsnDesc) && rsnDesc.length() > 250){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, SysLogConstant.LOG_CUST_VALID_RSN_DESC);
		}
		
		CstCommRecVO entity = new CstCommRecVO();
		entity.setCommDt(DateUtils.formatStringToDate(commDt, DateUtils.YYYY_MM_DD));
		entity.setCommWayCd(commWayCd);
		entity.setRespPsn(respPsn);
		entity.setLinkman(linkman);
		entity.setContactNum(contactNum);
		entity.setBriefRec(briefRec);
		entity.setFeedbackRec(feedbackRec);
		entity.setRsnDesc(rsnDesc);
		entity.setCstId(Long.valueOf(cstId));
		entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		entity.setMdfTm(new Date());//不论是新增还是修改,修改的时间都要存在
		entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());//同上
		return entity;
	}
}

